package com.city.dispatch.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.Circle;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.city.dispatch.R;
import com.city.dispatch.activity.HistoryRoadFiltateActivity;
import com.city.dispatch.base.BaseFragment;
import com.city.dispatch.base.BaseViewAdapter;
import com.city.dispatch.base.BaseViewHolder;
import com.city.dispatch.core.common.HttpHelper;
import com.city.dispatch.core.common.SharedPreferencesUrls;
import com.city.dispatch.core.common.UIHelper;
import com.city.dispatch.core.common.Urls;
import com.city.dispatch.core.widget.LoadingDialog;
import com.city.dispatch.model.GlobalConfig;
import com.city.dispatch.model.ResultConsel;
import com.city.dispatch.model.UnbindBean;
import com.city.dispatch.utils.LogUtil;
import com.google.gson.Gson;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONArray;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;

@SuppressLint("NewApi")
public class EbikeUnbindFragment extends BaseFragment implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener,
        AdapterView.OnItemClickListener{

    Unbinder unbinder;

    private Context context;
    private Activity activity;

//    @BindView(R.id.Layout_swipeListView)
    ListView listview;
//    @BindView(R.id.Layout_swipeParentLayout)
    SwipeRefreshLayout swipeRefreshLayout;
//    @BindView(R.id.msgText)
//    TextView msgText;

    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);
    private boolean mFirstFix = true;
    private LatLng myLocation = null;
    private Circle mCircle;
    private BitmapDescriptor successDescripter;
    private BitmapDescriptor bikeDescripter;
    private Handler handler = new Handler();
    private Marker centerMarker;
    private boolean isMovingMarker = false;

    private List<Marker> bikeMarkerList;
    private boolean isUp = false;

    private double latitude = 0.0;
    private double longitude = 0.0;
    private int isLock = 0;
    private View v;

    private LoadingDialog loadingDialog;
    private Dialog dialog;
    private List<UnbindBean> datas;
    private MyAdapter myAdapter;
    private int curPosition = 0;
    private int showPage = 1;
    private boolean isRefresh = true;// 是否刷新中
    private boolean isLast = false;

    private View footerView;
    private View footerViewType01;
    private View footerViewType02;
    private View footerViewType03;
    private View footerViewType04;
    private View footerViewType05;

    private ImageView iv_type05;
    private TextView tv_type05;

    private View footerLayout;

    private String badtime="2115-02-08 20:20";
    private String codenum="";
    private String totalnum="";

//    private String card_code;
    private String price;

    public String data;

    private String begintime;
    private String endtime;

    LinearLayout ll_day;
    TextView tv_day;

    private String timeJson;

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        v = inflater.inflate(R.layout.fragment_ebike_unbind, null);
        unbinder = ButterKnife.bind(this, v);

        return v;
    }


    @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context = getActivity();
        activity = getActivity();
        datas = new ArrayList<>();

        Log.e("euf===Created", "===");

        initView();

        Log.e("euf===Created2", "===");

//        initHttp();

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//
//            while (true){
//
//                try {
//                    Thread.sleep(30*1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//
//                m_myHandler.sendEmptyMessage(1);
//            }
//
//            }
//        }).start();

    }

    protected Handler m_myHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message mes) {
            switch (mes.what) {
                case 0:
                    break;
                case 1:
                    resetList();

                    break;
                default:
                    break;
            }
            return false;
        }
    });

    public void resetList(){
        showPage = 1;
        badtime="2115-02-08 20:20";

        Log.e("resetList===",isRefresh+"==="+datas+"==="+showPage+"==="+timeJson);

        if(datas.size()!=0){
            myAdapter.getDatas().clear();
            myAdapter.notifyDataSetChanged();
        }
        isRefresh = true;
        initHttp();

//        if (!isRefresh) {
//            if(datas.size()!=0){
//                myAdapter.getDatas().clear();
//                myAdapter.notifyDataSetChanged();
//            }
//            isRefresh = true;
//            initHttp();
//        } else {
//            swipeRefreshLayout.setRefreshing(false);
//        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);

        Log.e("euf===onHidden", "==="+hidden);

        if(hidden){
            //pause
        }else{
            //resume
//            resetList();
        }
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        isRefresh = true;
//        if(datas.size()!=0){
//            myAdapter.notifyDataSetChanged();
//        }
//    }


    private void initView(){
        loadingDialog = new LoadingDialog(context);
        loadingDialog.setCancelable(false);
        loadingDialog.setCanceledOnTouchOutside(false);

//        dialog = new Dialog(context, R.style.main_publishdialog_style);
//        View tagView = LayoutInflater.from(context).inflate(R.layout.dialog_deduct_mark, null);
//        dialog.setContentView(tagView);
//        dialog.setCanceledOnTouchOutside(false);

//        ll_day = (LinearLayout) activity.findViewById(R.id.ll_day);
        tv_day = (TextView) activity.findViewById(R.id.tv_day);

        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        String dateString="";
        try {
            calendar.add(calendar.DATE,1);//把日期往后增加一天.整数往后推,负数往前移动
            date=calendar.getTime(); //这个时间就是日期往后推一天的结果
            endtime = simpleDateFormat.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }

        Date datenow = new Date(System.currentTimeMillis());
        begintime = simpleDateFormat.format(datenow);

        Log.e("cia===onCreate", begintime+"==="+endtime);

        tv_day.setText(begintime+"到"+endtime);

        Gson gson = new Gson();
        List<String> timeList = new ArrayList<>();
        timeList.add(begintime);
        timeList.add(endtime);

        timeJson = gson.toJson(timeList);


        footerView = LayoutInflater.from(context).inflate(R.layout.footer_item, null);
        footerViewType01 = footerView.findViewById(R.id.footer_Layout_type01);// 点击加载更多
        footerViewType02 = footerView.findViewById(R.id.footer_Layout_type02);// 正在加载，请您稍等
        footerViewType03 = footerView.findViewById(R.id.footer_Layout_type03);// 已无更多
        footerViewType04 = footerView.findViewById(R.id.footer_Layout_type04);// 刷新失败，请重试
        footerViewType05 = footerView.findViewById(R.id.footer_Layout_type05);// 暂无数据

        footerLayout = footerView.findViewById(R.id.footer_Layout);

//        footerLayout = footerView.findViewById(R.id.footer_Layout);
//        footerViewType01.setVisibility(View.GONE);

//        iv_type05 = footerView.findViewById(R.id.footer_Layout_iv_type05);
//        tv_type05 = footerView.findViewById(R.id.footer_Layout_tv_type05);
//        iv_type05.setImageResource(R.drawable.no_card_icon);      //TODO
//        tv_type05.setText("暂无套餐卡");

//        footerLayout.setVisibility(View.VISIBLE);
//        setFooterType(4);

        swipeRefreshLayout = (SwipeRefreshLayout)getActivity().findViewById(R.id.Layout_swipeParentLayout);
        listview = (ListView)getActivity().findViewById(R.id.Layout_swipeListView);
        listview.addFooterView(footerView);

        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setColorSchemeColors(getResources().getColor(android.R.color.holo_green_dark), getResources().getColor(android.R.color.holo_green_light),
                getResources().getColor(android.R.color.holo_orange_light), getResources().getColor(android.R.color.holo_red_light));

//        JSONArray array = null;
//        try {
////            array = new JSONArray(data);
////
////            if (array.length() == 0) {
////
////                footerLayout.setVisibility(View.VISIBLE);
////                setFooterType(4);
////
////            }else{
////                footerLayout.setVisibility(View.GONE);
////            }
////
////            for (int i = 0; i < array.length();i++){
////                UnbindBean bean = JSON.parseObject(array.getJSONObject(i).toString(), UnbindBean.class);
////
////                datas.add(bean);
////            }
//
//            Log.e("euf===initView", "===");
//
//            UnbindBean bean = new UnbindBean();
//            datas.add(bean);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }

//        myAdapter.notifyDataSetChanged();

//        if(datas.isEmpty()){
//            initHttp();
//        }

        myAdapter = new MyAdapter(context);
        myAdapter.setDatas(datas);
        listview.setAdapter(myAdapter);

        tv_day.setOnClickListener(this);
        footerLayout.setOnClickListener(this);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                curPosition = position;
//                WindowManager.LayoutParams params1 = dialog.getWindow().getAttributes();
//                params1.width = LinearLayout.LayoutParams.MATCH_PARENT;
//                params1.height = LinearLayout.LayoutParams.MATCH_PARENT;
//                dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
//                dialog.getWindow().setAttributes(params1);
//                dialog.show();

//                Intent intent = new Intent(context, PayMontCartActivity.class);
//                startActivity(intent);
            }
        });
    }

    @Override
    public void onRefresh() {
        showPage = 1;
        if (!isRefresh) {
            if(datas.size()!=0){
                myAdapter.getDatas().clear();
                myAdapter.notifyDataSetChanged();
            }
            isRefresh = true;
            initHttp();
        } else {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    }

    @SuppressLint("NewApi")
    private class MyAdapter extends BaseViewAdapter<UnbindBean> {

        private LayoutInflater inflater;

        public MyAdapter(Context context){
            super(context);
            this.inflater = LayoutInflater.from(context);
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            if (null == convertView) {
                convertView = inflater.inflate(R.layout.item_ebike_unbind, null);
            }

            Log.e("euf===getView", "==="+position);

            TextView tv_day = BaseViewHolder.get(convertView,R.id.item_day);
            TextView tv_carmodel_name = BaseViewHolder.get(convertView,R.id.item_carmodel_name);
            TextView tv_number = BaseViewHolder.get(convertView,R.id.item_number);
            TextView tv_lock_name = BaseViewHolder.get(convertView,R.id.item_lock_name);
            TextView tv_deviceuuid = BaseViewHolder.get(convertView,R.id.item_deviceuuid);
            TextView tv_created_at = BaseViewHolder.get(convertView,R.id.item_created_at);

            final UnbindBean bean = getDatas().get(position);

            tv_day.setText(bean.getCreated_at().split(" ")[0]);
            tv_carmodel_name.setText(bean.getCarmodel_name());
            tv_number.setText(bean.getNumber());
            tv_lock_name.setText(bean.getLock_name());
            tv_deviceuuid.setText(bean.getVendor_lock_id());
            tv_created_at.setText(bean.getCreated_at());




            return convertView;
        }
    }




    private void initHttp(){
        String access_token = SharedPreferencesUrls.getInstance().getString("access_token","");
        if (access_token == null || "".equals(access_token)){
            Toast.makeText(context,"请先登录账号",Toast.LENGTH_SHORT).show();
            return;
        }
        RequestParams params = new RequestParams();
        params.put("time", timeJson);
        params.put("page", showPage);
        params.put("per_page", GlobalConfig.PAGE_SIZE);

        Log.e("euf===",showPage+"==="+timeJson);

        HttpHelper.get(context, Urls.untieCar_list, params, new TextHttpResponseHandler() {
            @Override
            public void onStart() {
                setFooterType(1);
            }
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                UIHelper.ToastError(context, throwable.toString());
                swipeRefreshLayout.setRefreshing(false);
                isRefresh = false;
                setFooterType(3);
                setFooterVisibility();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                try {
                    Log.e("euf===1","==="+responseString);
//                    {"id":4,"number":"30005061","carmodel_id":1,"carmodel_name":"\u5355\u8f66","school_id":10,"school_name":"\u6c5f\u82cf\u7406\u5de5\u5b66\u9662","school_area":"","lock_id":6,"lock_name":"lp_new","lock_title":"\u65b0\u6cfa\u5e73\u9501","vendor_lock_id":"0000","lock_no":"GpDTxfB76","lock_mac":"A4:34:F1:7C:1E:FA","lock_password":"***","lock_secretkey":"MzkzNDM3MzQ0MzQxMzMzNDMzNDI0MjMyNDQ0NjM2NDE0MjM3MzMzMjM1NDE0NTQ1MzM0NDM4Mzk0MzAw","admin_id":2,"admin_name":"yx","admin_phone":"18151207269","created_at":"2021-01-19 16:48:20"}

                    ResultConsel result = JSON.parseObject(responseString, ResultConsel.class);

                    JSONArray array = new JSONArray(result.getData());
                    if (array.length() == 0 && showPage == 1) {
                        footerLayout.setVisibility(View.VISIBLE);
                        setFooterType(4);
                        return;
                    } else if (array.length() < GlobalConfig.PAGE_SIZE && showPage == 1) {
                        footerLayout.setVisibility(View.GONE);
                        setFooterType(5);
                    } else if (array.length() < GlobalConfig.PAGE_SIZE) {
                        footerLayout.setVisibility(View.VISIBLE);
                        setFooterType(2);
                    } else if (array.length() >= GlobalConfig.PAGE_SIZE) {
                        footerLayout.setVisibility(View.VISIBLE);
                        setFooterType(0);
                    }

                    Log.e("euf===2","==="+array.length());

                    if(datas!=null && datas.size()>0){
                        datas.clear();
                    }

                    for (int i = 0; i < array.length();i++){
                        UnbindBean bean = JSON.parseObject(array.getJSONObject(i).toString(), UnbindBean.class);
                        datas.add(bean);

                        Log.e("euf===3","==="+datas);
                    }

//                    myAdapter.setDatas(datas);
//                    myAdapter.notifyDataSetChanged();

                } catch (Exception e) {
                    footerLayout.setVisibility(View.VISIBLE);
                    setFooterType(4);
                } finally {
                    swipeRefreshLayout.setRefreshing(false);
                    isRefresh = false;
                    setFooterVisibility();
                }
                if (loadingDialog != null && loadingDialog.isShowing()){
                    loadingDialog.dismiss();
                }
            }
        });
    }


    private void setFooterType(int type) {
        switch (type) {
            case 0:
                isLast = false;
                footerViewType01.setVisibility(View.VISIBLE);
                footerViewType02.setVisibility(View.GONE);
                footerViewType03.setVisibility(View.GONE);
                footerViewType04.setVisibility(View.GONE);
                footerViewType05.setVisibility(View.GONE);
                break;
            case 1:
                isLast = false;
                footerViewType01.setVisibility(View.GONE);
                footerViewType02.setVisibility(View.VISIBLE);
                footerViewType03.setVisibility(View.GONE);
                footerViewType04.setVisibility(View.GONE);
                footerViewType05.setVisibility(View.GONE);
                break;
            case 2:
                isLast = true;
                footerViewType01.setVisibility(View.GONE);
                footerViewType02.setVisibility(View.GONE);
                footerViewType03.setVisibility(View.VISIBLE);
                footerViewType04.setVisibility(View.GONE);
                footerViewType05.setVisibility(View.GONE);
                break;
            case 3:
                isLast = false;
                // showPage -= 1;
                footerViewType01.setVisibility(View.GONE);
                footerViewType02.setVisibility(View.GONE);
                footerViewType03.setVisibility(View.GONE);
                footerViewType04.setVisibility(View.VISIBLE);
                footerViewType05.setVisibility(View.GONE);
                break;
            case 4:
                isLast = true;
                footerViewType01.setVisibility(View.GONE);
                footerViewType02.setVisibility(View.GONE);
                footerViewType03.setVisibility(View.GONE);
                footerViewType04.setVisibility(View.GONE);
                footerViewType05.setVisibility(View.VISIBLE);
                break;
            case 5:
                isLast = true;
                footerViewType01.setVisibility(View.GONE);
                footerViewType02.setVisibility(View.GONE);
                footerViewType03.setVisibility(View.GONE);
                footerViewType04.setVisibility(View.GONE);
                footerViewType05.setVisibility(View.GONE);
                break;
        }
    }

    private void setFooterVisibility() {
        if (footerView.getVisibility() == View.GONE) {
            footerView.setVisibility(View.VISIBLE);
        }
    }





    @Override
    public void onResume() {
        super.onResume();
        isRefresh = true;
    }



    @Override
    public void onClick(View v) {
        String uid = SharedPreferencesUrls.getInstance().getString("uid","");
        String access_token = SharedPreferencesUrls.getInstance().getString("access_token","");
        switch (v.getId()){

            case R.id.footer_Layout:
                if (!isLast) {
                    showPage += 1;
                    initHttp();
                    myAdapter.notifyDataSetChanged();
                }
                break;

            case R.id.tv_day:
                Intent intent = new Intent(context, HistoryRoadFiltateActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivityForResult(intent,0);
                break;

            default:
                break;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }
    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent idata) {

        Log.e("requestCode===", "==="+requestCode);

        switch (requestCode) {
            case 0:
                if (idata != null) {
                    begintime = idata.getExtras().getString("starttime");
                    endtime = idata.getExtras().getString("endtime");

                    tv_day.setText(begintime+" 到 "+endtime);

                    LogUtil.e("onActivityResult===",begintime+"==="+endtime+"==="+data);

                    Gson gson = new Gson();
                    List<String> timeList = new ArrayList<>();
                    timeList.add(begintime);
                    timeList.add(endtime);

                    timeJson = gson.toJson(timeList);

//                    onRefresh();

                    if(datas.size()!=0){
                        myAdapter.getDatas().clear();
                        myAdapter.notifyDataSetChanged();
                    }
                    initHttp();
                }
                break;

            case 1:
                if (resultCode == RESULT_OK) {
                    String result = idata.getStringExtra("QR_CODE");
                } else {
					Toast.makeText(context, "扫描取消啦!", Toast.LENGTH_SHORT).show();
                }

                Log.e("requestCode===1", "==="+resultCode);
                break;

            default:
                break;

        }
    }


}
